package com.opdar.plugins.mybatis.core;

import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;

import java.io.ByteArrayInputStream;
import java.util.List;

/**
 * Created by jeffrey on 2016/11/13.
 */
public class InputStreamExector {

    public static Resource[] mergeResource(Resource[] mapperLocation, List<Class<?>> mappers) {
        Resource[] dest = new Resource[mapperLocation.length+mappers.size()];
        System.arraycopy(mapperLocation,0,dest,0,mapperLocation.length);
        for(int i = 0;i<mappers.size();i++){
            Class<?> mapper = mappers.get(i);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(("<?xml version=\"1.0\" encoding=\"utf-8\"?><!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\"><mapper namespace=\""+mapper.getName()+"\"></mapper>").getBytes());
            dest[mapperLocation.length+i] = new InputStreamResource(inputStream,mapper.getName());
        }
        return dest;
    }

    public static Resource encode(Resource mapperLocation,String tablePrefix,String databaseName) {

        ResultMapperParser parser = new ResultMapperParser();
        try {
            parser.init(tablePrefix, databaseName);
            ByteArrayInputStream baos = parser.parse(mapperLocation.getInputStream());
            if (baos != null) return new MapperResource(baos,mapperLocation.getDescription());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
